/**
 * 583. 两个字符串的删除操作
 * 中等
 * <p>
 * 给定两个单词 word1 和 word2 ，返回使得 word1 和  word2 相同所需的最小步数。
 * <p>
 * 每步 可以删除任意一个字符串中的一个字符。
 * <p>
 * <p>
 * <p>
 * 示例 1：
 * <p>
 * 输入: word1 = "sea", word2 = "eat"
 * 输出: 2
 * <p>
 * 解释: 第一步将 "sea" 变为 "ea" ，第二步将 "eat "变为 "ea"
 * 示例  2:
 * <p>
 * 输入：word1 = "leetcode", word2 = "etco"
 * 输出：4
 * <p>
 * <p>
 * 提示：
 * <p>
 * 1 <= word1.length, word2.length <= 500
 * word1 和 word2 只包含小写英文字母
 */

public class DeleteOperationForTwoStrings {
    public static void main(String[] args) {
        System.out.println(minDistance("leetcode", "etco"));
        System.out.println(minDistance("sea", "eat"));
        System.out.println(minDistance("a", "b"));
        System.out.println(minDistance("asdasdazxsawdaawrqwdxwda", "xasdacjiasonushfcasiufgijdwe"));
    }

    public static int minDistance(String word1, String word2) {
        return process(word1, word2);
    }

    private static int process(String word1, String word2) {
        char[] char1Array = word1.toCharArray();
        char[] char2Array = word2.toCharArray();
        int[][] dp = new int[char1Array.length + 1][char2Array.length + 1];

        //dp[i][j] 表示取 word1 前 i 个字符和 word2 取前 j 个字符的最小变化数
        for (int i = 0; i <= char1Array.length; i++) {
            dp[i][0] = i;
        }
        for (int i = 0; i <= char2Array.length; i++) {
            dp[0][i] = i;
        }
        for (int i = 1; i < dp.length; i++) {
            for (int j = 1; j < dp[i].length; j++) {
                if (char2Array[j - 1] == char1Array[i - 1]) {
                    dp[i][j] = dp[i - 1][j - 1];
                } else {
                    dp[i][j] = dp[i - 1][j - 1] + 2;
                }
                dp[i][j] = Math.min(Math.min(dp[i - 1][j], dp[i][j - 1]) + 1, dp[i][j]);
            }
        }
        return dp[char1Array.length][char2Array.length];
    }
}
